package com.eric.ddd.regist;

import javax.xml.bind.ValidationException;
import java.util.Arrays;

/**
 * @author eric
 * Description: 注册接口
 */
public class RegistrationServiceImpl implements RegistrationService {

    private SalesRepRepository salesRepRepo;
    private UserRepository userRepo;

    /**
     * 注册
     *
     * @param name    用户名
     * @param phone   手机号码
     * @param address 地址
     * @return 注册用户
     */
    @Override
    public User register(String name, String phone, String address) throws ValidationException {
        // 1. 校验逻辑
        if (name == null || name.length() == 0) {
            throw new ValidationException("name is null.");
        }
        if (phone == null || !isValidPhoneNumber(phone)) {
            throw new ValidationException("phone");
        }

        // 此处省略address的校验逻辑

        // 2. 取电话里的区号，然后听过区号找打区域内的SalesResp
        String areaCode = null;
        String[] areas = new String[]{"0571", "021", "010"};
        for (int i = 0; i < phone.length(); i++) {
            String prefix = phone.substring(0, i);
            if (Arrays.asList(areas).contains(prefix)) {
                areaCode = prefix;
                break;
            }
        }
        SalesRep rep = salesRepRepo.findRep(areaCode);

        // 3. 最后创建用户返回
        // 最后创建用户，落盘，然后返回
        User user = new User();
        user.name = name;
        user.phone = phone;
        user.address = address;
        if (rep != null) {
            user.repId = rep.repId;
        }

        return userRepo.save(user);
    }

    /**
     * 校验手机号码
     *
     * @param phone 手机号码
     * @return 是否通过
     */
    private boolean isValidPhoneNumber(String phone) {
        String pattern = "^0[1-9]{2,3}-?\\d{8}$";
        return phone.matches(pattern);
    }

}
